/*
 * Created on 2005-7-1
 */
package com.maxjay.common.exception.processor;

import java.sql.SQLException;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.HashMap;

import com.maxjay.common.exception.ERR;

/**
 * <p>
 * Title: 框架
 * </p>
 * <p>
 * Description: 通过定义SQLException的信息, 来返回自定义的错误信息
 * </p>
 * Mapping the Exception to ErrCode which is hold in ERR.
 * <p>
 * Copyright: Copyright (c) 2005
 * </p>
 * <p>
 * Company: 公司
 * </p>
 * 
 * @author 郑美旺
 * @version 1.0
 */
public class SQLExceptionProcessor {
	// singleton with a eager initialization.
	private static SQLExceptionProcessor theInstance = new SQLExceptionProcessor();

	public static SQLExceptionProcessor getInstance() {
		return theInstance;
	}

	// Exception 2 ErrCode mapping
	private HashMap<String, Integer> errCode;

	private SQLExceptionProcessor() {

		// the sqlState-oracleErr mapping is listed at
		// http://www-rohan.sdsu.edu/doc/oracle/server803/A54660_01/appd.htm

		errCode = new HashMap<String, Integer>();
		// unique constraint violated
		errCode.put("ORA-00000", new Integer(ERR.DB_CONNECTION_FULL));
		errCode.put("ORA-00001", new Integer(ERR.DB_SAME_PK));
		errCode.put("ORA-00917", new Integer(ERR.DB_INVALID_QUERY));
		// insert null value to not allowed null field
		errCode.put("ORA-01400", new Integer(ERR.DB_FIELD_NOT_NULL));
		// inserted value too large for column
		errCode.put("ORA-01401", new Integer(ERR.DB_TOO_LARGE_VALUE));
		// inserted value too large to numer column
		errCode.put("ORA-01438", new Integer(ERR.DB_TOO_LARGE_VALUE));
		// sequence does not exist
		errCode.put("ORA-02289", new Integer(ERR.DB_SEQUENCE_ERROR));
		//foreign key violated
		errCode.put("ORA-02291", new Integer(ERR.DB_FOREIGN_KEY_CONSTRAINT));
		// sequence exceeds MAXVALUE and cannot be instantiated
		errCode.put("ORA-08004", new Integer(ERR.DB_SEQUENCE_ERROR));
		// 无效的标识符
		errCode.put("ORA-00904", new Integer(ERR.DB_NO_FIELD));

		
	}

	public int getGeneExceptionErrorCode(SQLException ex) {
		NumberFormat formatter = new DecimalFormat("00000");
		String cde = formatter.format(ex.getErrorCode());
		Integer cdeDefined = (Integer) errCode.get("ORA-" + cde);
		if (cdeDefined != null)
			return cdeDefined.intValue();
		else
			return ERR.DB_ERROR;
	}
}
